package yiran.stock;

import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import yiran.stock.data.DatabaseManager;
import yiran.stock.gui.StockGUI;
import yiran.stock.output.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ConfigManager {
    private final JavaPlugin plugin;
    private Material guiOpenItem;

    public ConfigManager(JavaPlugin plugin) {
        this.plugin = plugin;
    }

    public void loadConfig() {
        plugin.saveDefaultConfig();
        File configFile = new File(plugin.getDataFolder(), "config.yml");
        FileConfiguration config = YamlConfiguration.loadConfiguration(configFile);

        try {
            guiOpenItem = Material.valueOf(config.getString("gui.open-item", "PAPER"));
        } catch (IllegalArgumentException e) {
            guiOpenItem = Material.PAPER;
            Logger.warn("无效的gui.open-item配置，使用默认值PAPER");
        }

        int itemsPerPage = config.getInt("gui.items-per-page", 28);
        StockGUI.setItemsPerPage(itemsPerPage);
    }
    
    public void createBackup() {
        if (DatabaseManager.getDbType() != DatabaseManager.DatabaseType.SQLITE) {
            return;
        }
        File dbFile = new File(plugin.getDataFolder(), "stock_data.db");
        File backupDir = new File(plugin.getDataFolder(), "backups");
        if (!backupDir.exists()) backupDir.mkdirs();
        
        File backupFile = new File(backupDir, "stock_data_" + System.currentTimeMillis() + ".db");
        try {
            Files.copy(dbFile.toPath(), backupFile.toPath());
        } catch (IOException e) {
            Logger.error("数据库备份失败: " + e.getMessage());
        }
    }
    
    public Material getGuiOpenItem() {
        return guiOpenItem;
    }
}
